package com.akk.business;

import com.akk.common.enums.UserEnums;
import com.akk.exception.RestBusinessException;
import com.akk.module.app.entity.AppUserGrade;
import com.akk.module.app.service.AppUserGradeService;
import com.akk.module.authentication.BankCardAuthService;
import com.akk.module.authentication.model.request.BankCardAuthRequest;
import com.akk.module.authentication.model.response.BankCardAuthResponse;
import com.akk.module.upload.service.PictureService;
import com.akk.module.user.entity.User;
import com.akk.module.user.entity.UserAgent;
import com.akk.module.user.model.request.AuthenticationRequest;
import com.akk.module.user.model.request.AutoAuthRequest;
import com.akk.module.user.model.request.ForgetTransPwdRequest;
import com.akk.module.user.model.request.UpdateTransPwdRequest;
import com.akk.module.user.model.response.SpreadUsersResponse;
import com.akk.module.user.model.response.UserResponse;
import com.akk.module.user.service.UserAgentService;
import com.akk.module.user.service.UserService;
import com.akk.utils.FileUtil;
import com.akk.utils.RestResponse;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserBusiness {

    @Autowired
    UserService userService;
    @Autowired
    UserAgentService userAgentService;
    @Autowired
    AppUserGradeService appUserGradeService;
    @Autowired
    PictureService pictureService;
    @Autowired
    BankCardAuthService bankCardAuthService;


    public UserResponse getUserInfo(User user) {
        UserResponse response = new UserResponse();
        response.setUserId(user.getUserId());
        response.setAgentId(user.getAgentId());
        response.setUsername(user.getUsername());
        UserAgent userAgent = userAgentService.findByAgentId(user.getAgentId());
        response.setAgentName(userAgent.getAgentName());
        response.setCreateDate(user.getCreateDate());
        response.setFacePath(user.getFacePath());
        response.setIdCard(user.getIdCard());
        response.setStatus(user.getStatus());
        response.setPhone(user.getPhone());
        response.setSpreadId(user.getSpreadId());
        User spreadUser = userService.findByUserId(user.getSpreadId());
        response.setSpreadName(spreadUser.getUsername());
        response.setSpreadPhone(spreadUser.getPhone());
        response.setRealAuth(user.getRealAuth());
        response.setAppId(user.getAppId());
        AppUserGrade appUserGrade = appUserGradeService.findByUserGradeId(user.getUserGradeId());
        response.setUserGradeId(appUserGrade.getUserGradeId());
        response.setUserGradeName(appUserGrade.getUserGradeName());
        return response;
    }

    public boolean updatePhone(String phone, String newPhone, String appId, HttpServletRequest request) {
        Object phoneSession = request.getSession().getAttribute(phone);
        Object newPhoneSession = request.getSession().getAttribute(newPhone);
        if (phoneSession == null || !(phoneSession).equals("success"))
            throw new RestBusinessException("手机号未通过验证或验证失效.");
        if (newPhoneSession == null || !(newPhoneSession).equals("success"))
            throw new RestBusinessException("新手机号未通过验证或验证失效.");
        //验证新手机号是否存在
        User userServer = userService.findByPhoneAndAppId(newPhone, appId);
        if (userServer != null)
            throw new RestBusinessException("手机号已被注册使用.");
        //验证手机号是否存在
        User user = userService.findByPhoneAndAppId(phone, appId);
        if (user == null)
            throw new RestBusinessException("用户信息不存在.");
        user.setPhone(newPhone);
        userService.update(user);
        return true;
    }

    public boolean updatePhoto(User user, MultipartFile photo) {

        if (photo == null)
            throw new RestBusinessException("参数缺失.");
        Map<String, Object> map = pictureService.uploadPicture(photo);
        if ((int) (map.get("status")) != 0)
            throw new RestBusinessException("头像上传失败.");
        user.setFacePath(map.get("url").toString());
        userService.update(user);
        return true;
    }

    public boolean updateTransPwd(User user, UpdateTransPwdRequest request) {
        request.setTransPwd(new Sha256Hash(request.getTransPwd()).toHex());
        request.setNewTransPwd(new Sha256Hash(request.getNewTransPwd()).toHex());
        request.setLoginPwd(new Sha256Hash(request.getLoginPwd()).toHex());
        if (!user.getLoginPwd().equals(request.getLoginPwd()))
            throw new RestBusinessException("登录密码不正确.");
        if (!StringUtils.isEmpty(user.getTransPwd()) && !request.getTransPwd().equals(user.getTransPwd()))
            throw new RestBusinessException("原交易密码错误.");
        user.setTransPwd(request.getNewTransPwd());
        userService.update(user);
        return true;
    }

    public boolean forgetTransPwd(User user, ForgetTransPwdRequest request, HttpServletRequest servletRequest) {
        if (!user.getIdCard().equals(request.getIdCard()))
            throw new RestBusinessException("身份证号错误.");
        if (!request.getCode().equals(servletRequest.getSession().getAttribute(request.getPhone())))
            throw new RestBusinessException("验证码错误.");
        servletRequest.getSession().removeAttribute(request.getPhone());
        user.setTransPwd(new Sha256Hash(request.getNewTransPwd()).toHex());
        userService.update(user);
        return true;
    }

    public boolean authentication(User user, AuthenticationRequest request) {
        if (user.getRealAuth() != null && user.getRealAuth() == -1)
            throw new RestBusinessException("您被拉入实名黑名单，请联系相关客服.");
        else if (user.getRealAuth() != null && user.getRealAuth() == 1)
            throw new RestBusinessException("已提交实名资料，请耐心等待审核.");
        else if (user.getRealAuth() != null && user.getRealAuth() == 2)
            throw new RestBusinessException("已经实名成功了，无需再次实名.");
        if (request.getBankIdCardBack() == null)
            throw new RestBusinessException("请上传银行卡身和份证背面.");
        if (request.getBankIdCardPos() == null)
            throw new RestBusinessException("请上传银行卡和身份证正面.");
        if (request.getHoldBankIdCardPos() == null)
            throw new RestBusinessException("请上传手持身份证和银行卡正面.");
        String filePost1 = FileUtil.getFilePostfix(request.getBankIdCardPos().getOriginalFilename());
        String filePost2 = FileUtil.getFilePostfix(request.getBankIdCardBack().getOriginalFilename());
        String filePost3 = FileUtil.getFilePostfix(request.getHoldBankIdCardPos().getOriginalFilename());
        String fileName1 = request.getUserName() + "_" + request.getIdCard() + "bankIdCardPost." + filePost1;
        String fileName2 = request.getUserName() + "_" + request.getIdCard() + "bankIdCardBack." + filePost2;
        String fileName3 = request.getUserName() + "_" + request.getIdCard() + "holdBankIdCardPost." + filePost3;
        if (!FileUtil.isImagePngJpg(fileName1) || !FileUtil.isImagePngJpg(fileName2) || !FileUtil.isImagePngJpg(fileName3))
            throw new RestBusinessException("请上传png或jpg格式的图片.");
        Map<String, Object> map1 = pictureService.uploadPicture(request.getBankIdCardPos()); // 身份证 银行卡 正面
        Map<String, Object> map2 = pictureService.uploadPicture(request.getBankIdCardBack()); // 身份证 银行卡 反面
        Map<String, Object> map3 = pictureService.uploadPicture(request.getHoldBankIdCardPos()); // 手持 身份证 银行卡 正面
        if ((int) map1.get("status") == 1)
            throw new RestBusinessException("银行卡身份证正面照上传失败.");
        if ((int) map2.get("status") == 1)
            throw new RestBusinessException("银行卡身份证背面照上传失败.");
        if ((int) map3.get("status") == 1)
            throw new RestBusinessException("手持身份证、银行卡照片上传失败.");
        user.setBankIdcardPos(map1.get("url").toString());
        user.setBankIdcardBack(map2.get("url").toString());
        user.setHoldBankIdcardPos(map3.get("url").toString());
        user.setRealAddr(request.getRealAddr());
        user.setRealType(UserEnums.RealType.ARTI.getValue());
        user.setRealAuth(UserEnums.RealAuth.DOING.getValue()); // -1 黑名单 0 未实名 1 提交审核中 2 实名通过
        user.setRealDate(new Date());
        userService.update(user);
        return true;
    }

    public RestResponse autoAuth(User user, AutoAuthRequest request) {
        if (user.getRealAuth().intValue() == UserEnums.RealAuth.SUCCESS.getValue())
            throw new RestBusinessException("实名通过，无需再次认证.");
        else if (user.getRealAuth().intValue() == UserEnums.RealAuth.BLACKLIST.getValue())
            throw new RestBusinessException("您已进入实名黑名单，请联系官方客服.");
        else if (user.getRealAuth().intValue() == UserEnums.RealAuth.DOING.getValue())
            throw new RestBusinessException("实名信息已经提交，请等待人工审核结果.");
        BankCardAuthRequest bankCardAuthRequest = new BankCardAuthRequest();
        bankCardAuthRequest.setBankCard(request.getBankCardNum());
        bankCardAuthRequest.setBankCardReason("实名认证");
        bankCardAuthRequest.setIdCard(request.getIdCard());
        bankCardAuthRequest.setMobile(request.getPhone());
        bankCardAuthRequest.setRealName(request.getRealName());
        bankCardAuthRequest.setType(4);
        BankCardAuthResponse bankCardAuthResponse = (BankCardAuthResponse) bankCardAuthService.auth(bankCardAuthRequest);
        if(bankCardAuthResponse != null&& "00".equals(bankCardAuthResponse.getRecord().get(0).getResCode())){
            user.setRealType(UserEnums.RealType.AUTO.getValue());
            user.setIdCard(request.getIdCard());
            user.setUsername(request.getMerName());
            user.setRealAuth(UserEnums.RealAuth.SUCCESS.getValue());
            user.setRealAddr(request.getAddress());
            user.setRealDate(new Date());
            userService.update(user);
            return RestResponse.build(bankCardAuthResponse);
        }else{
            return RestResponse.build(bankCardAuthResponse);
        }
    }

    public SpreadUsersResponse mySpreadUsers(User user) {
        List<String> userIds = new ArrayList<>();
        userIds.add(user.getUserId());
        List<User> downOneUsers = userService.findByAppIdAndSpreadIds(user.getAppId(), userIds);
        userIds.removeAll(userIds);
        for (User spreadUser : downOneUsers) {
            if (downOneUsers.size() == 0)
                break;
            userIds.add(spreadUser.getUserId());
        }

        List<User> downTwoUsers = new ArrayList<>();
        if (userIds.size() != 0) {
            downTwoUsers = userService.findByAppIdAndSpreadIds(user.getAppId(), userIds);
        }
        userIds.removeAll(userIds);
        for (User spreadUser : downTwoUsers) {
            if (downTwoUsers.size() == 0)
                break;
            userIds.add(spreadUser.getUserId());
        }
        List<User> downThreeUsers = new ArrayList<>();
        if (userIds.size() != 0) {
            downThreeUsers = userService.findByAppIdAndSpreadIds(user.getAppId(), userIds);
        }
        userIds.clear();
        SpreadUsersResponse response = new SpreadUsersResponse();
        response.setDownOneUsers(downOneUsers);
        response.setDownTwoUsers(downTwoUsers);
        response.setDownThreeUsers(downThreeUsers);
        return response;
    }
}
